#!/usr/bin/env bash
set -e
mkdir -p /opt/tmp/
mkdir -p /opt/script/


wget http://mirrors.tuna.tsinghua.edu.cn/apache/kafka/0.11.0.1/kafka_2.11-0.11.0.1.tgz
tar -zxvf kafka_2.11-0.11.0.1.tgz

mv kafka_2.11-0.11.0.1/ /opt/kafka
mv kafka_2.11-0.11.0.1.tgz /opt/tmp/


num=`cat config.json  |jq '.server | length'`
#主题可删除
sed -i "s/#delete.topic.enable=true/delete.topic.enable=true/g"  /opt/kafka/config/server.properties

zk=""
#zk集群
for((i=0;i<$num;i++))
do
host=`cat config.json  |jq ".server[$i].host"`
ip=`cat config.json  |jq ".server[$i].ip"`
if  [ "\""`hostname`"\"" = ${host} ]
then
#        EPS主机
        zk="${zk}${host}:2181"
        sed -i "s/\(broker.id*=\).*/\1 ${i} /g"  /opt/kafka/config/server.properties
  #       echo -e "
#advertised.host.name=${ip}" | sed 's/\"//g'  >> /opt/kafka/config/server.properties

else
        zk="${zk}${host}:2181"
fi
r=`expr $num  - $i `

if [ $r != 1  ]
then
        zk="${zk},"
fi
done

sed -i "s/\(zookeeper.connect*=\).*/\1 `echo ${zk} | sed 's/\"//g' ` /g"  /opt/kafka/config/server.properties



#启动脚本
echo -e "#!/bin/env bash
/opt/kafka/bin/kafka-server-start.sh -daemon /opt/kafka/config/server.properties
">> /opt/script/kafkaup.sh

#停止脚本
echo -e "#!/bin/env bash
/opt/kafka/bin/kafka-server-stop.sh
">> /opt/script/kafkadown.sh

#删除脚本
echo -e "#!/bin/env bash
/opt/kafka/bin/kafka-server-stop.sh
rm -rf /opt/kafka
rm -rf /opt/script/kafkaup.sh
rm -rf opt/script/kafkadown.sh
rm -rf /opt/script/kafkauninstall.sh
">> /opt/script/kafkauninstall.sh






#kafka-server-start.sh config/server.properties
#/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties
#kafka-topics.sh --create --zookeeper 47.52.164.135:2181,111.231.197.148:2181,45.32.106.16:2181 --replication-factor 3 --partitions 3 --topic test
#kafka-console-consumer.sh --zookeeper 47.52.164.135:2181,111.231.197.148:2181,45.32.106.16:2181 -topic test --from-beginning
#EPS安装
#server-pro   zoo-con    127.0.0.1@2181,hk:*****
#echo advertised.host.name = zookeeper IP
#http://jicki.blog.51cto.com/1323993/1651206
#https://stackoverflow.com/questions/34572621/cant-connect-to-kafka-server
#2、查看所有主题
#【命令方式】：/opt/kafka/bin/kafka-topics.sh --list --zookeeper localhost:2181
#3、查看指定主题：
#【命令方式】：bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic 主题名
#4、修改主题：
#【命令方式】：bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic 主题名 --deleteConfig x
#5 查看主题分区
#./kafka-topics.sh --describe --zookeeper localhost

#kafka命令
#http://www.jianshu.com/p/77bf90cdae0d